<?php if (!defined("BASEPATH")) exit("No direct script access allowed"); ?>

<? // Common::pr($getCategory ); exit; ?>

<script type="text/javascript">
	Ext.onReady(function() {

		var winCategory; // edit ablak
		var categoryForm; // form panel

		var reader = new Ext.data.ArrayReader({}, [
			{name: 'catId'},
			{name: 'catName'},
			{name: 'catType'},
			{name: 'catLength'},
			{name: 'catTypeLname'},
			{name: 'catEntity'},
			{name: 'catEntityLname'},
			{name: 'catOrder'},
			{name: 'catList'},
			{name: 'catRequired'},
			{name: 'catHighlight'}
		]);

		var store = new Ext.data.GroupingStore({
			reader: reader,
			data: [
				<?
					$first = TRUE;
					foreach($getCategory as $entity => $category) {
						foreach($category as $ii => $d) {
							echo	((!$first)?(","):(""))."[\"".$d["catId"]."\", \"".$this->db->escape_str($d["catName"])."\", \"".$d["catType"]."\", \"".$d["catLength"]."\", \"".$d["catTypeLname"]."\", \"".$d["catEntity"]."\", \"".$d["catEntityLname"]."\", ".$d["catOrder"].", \"".$this->db->escape_str($d["catList"])."\", \"".$d["catRequired"]."\", \"".$d["catHighlight"]."\"]";
							$first = FALSE;
						}
					}
				?>
			],
			sortInfo:{field: 'catOrder', direction: "ASC"},
			groupField:'catEntityLname'
		});

		var grid = new Ext.grid.GridPanel({
			store: store,
			id: 'gridCategory',
			viewConfig:{
				emptyText: '<?=$this->db->escape_str($this->lang->line("THERE_IS_CURRENTLY_NO_DATA_TO_DISPLAY"))?>'
			},

			view: new Ext.grid.GroupingView({
				forceFit:true,
				startCollapsed: true,
				groupTextTpl: '{text} ({[values.rs.length]} {["<?=$this->db->escape_str($this->lang->line("ITEM"))?>"]})'
			}),

			columns: [
				{id:'catEntityLname', header: '<?=$this->db->escape_str($this->lang->line("CATEGORY"))?>', hidden: true, width: 100, sortable: true,  dataIndex: 'catEntityLname'},
				{id: 'catName', header: '<?=$this->db->escape_str($this->lang->line("NAME"))?>', width: 200, sortable: false, dataIndex: 'catName'},
				{header: '<?=$this->db->escape_str($this->lang->line("TYPE"))?>', width: 100, sortable: false, dataIndex: 'catTypeLname'},
				{header: '<?=$this->db->escape_str($this->lang->line("LENGTH"))?>', width: 30, sortable: false, dataIndex: 'catLength'},
				{header: '<?=$this->db->escape_str($this->lang->line("REQUIRED"))?>', width: 70, align: 'center', sortable: true, dataIndex: 'catRequired', renderer: function(val) { return '<span' + ((val == 'I')?(' style="color:green;"'):('')) + '>' + ((val == 'I')?('<?=$this->db->escape_str($this->lang->line("YES"))?>'):('<?=$this->db->escape_str($this->lang->line("NO"))?>')) + '</span>';}},
				{header: '<?=$this->db->escape_str($this->lang->line("EMPHASIZED"))?>', width: 70, align: 'center', sortable: true, dataIndex: 'catHighlight', renderer: function(val, cell, record) { if(record.data.catEntity != 'MAJ') return ''; return '<span' + ((val == 'I')?(' style="color:green;"'):('')) + '>' + ((val == 'I')?('<?=$this->db->escape_str($this->lang->line("YES"))?>'):('<?=$this->db->escape_str($this->lang->line("NO"))?>')) + '</span>';}}
			],
			stripeRows: true,
			autoExpandColumn: 'catName',
			autoHeight: true,
			autoWidth: true,
			enableDragDrop: true,
			ddGroup: 'myddGroup',
			sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
			listeners: {

				render: function() {

					grid.dropZone = new Ext.dd.DropZone(grid.getView().scroller, {

						ddGroup: 'myddGroup',

						getTargetFromEvent: function(e) {
							return e.getTarget(grid.getView().rowSelector);
						},

						onNodeEnter : function(target, dd, e, data){ 
							Ext.fly(target).addClass('my-row-highlight-class');
						},

						onNodeOut : function(target, dd, e, data){ 
							Ext.fly(target).removeClass('my-row-highlight-class');
						},

						onNodeOver : function(target, dd, e, data){ 
							return Ext.dd.DropZone.prototype.dropAllowed;
						},

						onNodeDrop : function(target, dd, e, data){

							if(dd.getDragData(e)) {
								var newpos = dd.getDragData(e).rowIndex + 1;
								var selectedCatId = grid.getStore().getAt(data.rowIndex).data.catId;
								if(grid.getStore().getAt(newpos-1).data.catEntity == grid.getStore().getAt(data.rowIndex).data.catEntity) {
									Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_CHANGE_THE_ORDER_OF_MENU_ITEMS_BELOW"))?><br/><br/><p style="text-align:center;"><b>' + grid.getStore().getAt(data.rowIndex).data.catName + '(' + grid.getStore().getAt(data.rowIndex).data.catOrder + ')</b> <?=$this->db->escape_str($this->lang->line("MOVE"))?> <b>' + grid.getStore().getAt(newpos-1).data.catName + '(' + grid.getStore().getAt(newpos-1).data.catOrder + ')</b> <?=$this->db->escape_str($this->lang->line("TO_POSITION"))?></p>', 
									function(btn) {
										if(btn == 'yes') {
											Ext.Ajax.request({url: '<?=site_url()?>admin/category_insert_update', params: 'sort=1&catId=' + selectedCatId + '&position=' + grid.getStore().getAt(newpos-1).data.catOrder, success: function() { Ext.get('center').load({url: '<?=site_url()?>admin/category', scripts:true}); }});
										} else {
											//alert(grid.getStore().getAt(newpos-1).data.catOrder);
										}
									});
								}
							}

						}
					});
				},

				rowdblclick: function(grid, rowIndex, event) {
					if(rowIndex != 'new') {
						var record = grid.getStore().getAt(rowIndex);
					} else {
						var record = new Object();
						record.data = new Object();
						//record.data.catEntity = grid.getId().replace('grid_', '');
					}

					if(winCategory) {
						winCategory.close();
					}
					winCategory = new Ext.Window({
						iconCls: (rowIndex == 'new')?('application_form_add'):('application_form_edit'),
						layout:'',
						bodyStyle: 'background-color:white',
						autoScroll: true,
						modal: true,
						width:500,
						floating: true,
						minWidth: 500,
						height:400,
						minHeight: 400,
						closeAction:'close',
						maximizable:true,
						title: (rowIndex == 'new')?('<?=$this->db->escape_str($this->lang->line("ADD_NEW_PROPERTY"))?>'):('<?=$this->db->escape_str($this->lang->line("EDITING_CATEGORY"))?> - ' + record.data.catName),

						listeners: {
							close: function() {
								Ext.getCmp('tabs').getActiveTab().getUpdater().refresh();
							}
						},

						items:[{

									border: false,

									items: categoryForm = new Ext.FormPanel({
										id: 'categoryForm',
										padding: 10,
										labelAlign: 'right',
										labelWidth: 110,
										autoHeight: true,
										autoWidth: true,
										border: false,
										defaultType: 'textfield',
										waitMsgTarget: true,
										items: [{
													hidden: true,
													inputType: 'hidden',
													name: 'cat_id',
													value: record.data.catId
											}, {
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("NAME_OF_CATEGORY"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [{
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("NAME_OF_CATEGORY"))?>',
													xtype: 'textfield',
													name: 'cat_name',
													value: record.data.catName,
													maxLength: 255,
													maxLengthText: '<?=$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))?>',
													allowBlank: false,
													blankText: '<?=$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))?>',
													anchor:'100%'
												}]
											}, {
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("TYPE"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [
													new Ext.form.ComboBox({
														fieldLabel: '<?=$this->db->escape_str($this->lang->line("TYPE"))?>',
														hiddenName:'cat_type',
														store: new Ext.data.ArrayStore({
															fields: ['cat_type_sname', 'cat_type_lname'],
															data : <? $szotar = Common::szotar("CATTYPE"); echo Common::arr2jsobj($szotar["CATTYPE"]); ?>
														}),
														listeners: {
															change: function(field, newValue, oldValue) {
																if(newValue == 'L') {
																	Ext.getCmp('cat_list').show();
																} else {
																	Ext.getCmp('cat_list').hide();
																}
															}
														},
														valueField:'cat_type_sname',
														displayField:'cat_type_lname',
														editable: false,
														mode: 'local',
														triggerAction: 'all',
														emptyText:'...',
														selectOnFocus:true,
														allowBlank: false,
														blankText: '<?=$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))?>',
														value: record.data.catType,
														anchor:'100%'
													})
												]
											}, {
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("LENGTH"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [{
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("LENGTH"))?>',
													xtype: 'numberfield',
													name: 'cat_length',
													value: record.data.catLength,
													maxLength: 255,
													maxLengthText: '<?=$this->db->escape_str($this->lang->line("YOU_HAVE_EXCEEDED_THE_MAXIMUM_LENGTH"))?>',
													allowBlank: true,
													anchor:'100%'
												}]
											}, {
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("LIST"))?>',
												autoHeight:true,
												hidden: ((record.data.catType && record.data.catType == 'L')?(false):(true)),
												id:'cat_list',
												layout: {
													type: 'anchor'
												},
												items: [{
													allowBlank: true, 
													xtype:'superboxselect',
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("LIST"))?>',
													resizable: true,
													name: 'cat_list[]',
													anchor:'100%',
													store: new Ext.data.ArrayStore({
														fields: ['id', 'cat_list'],
														url: '<?=site_url()?>admin/getCatList/' + ((record.data.catList)?(record.data.catList):('')),
														autoLoad: true
													}),
													valueDelimiter: '|',
													value: record.data.catList,
													mode: ((rowIndex == 'new')?('local'):('remote')),
													triggerAction: 'all',
													displayField: 'cat_list',
													displayFieldTpl: '{cat_list}',
													valueField: 'cat_list',
													navigateItemsWithTab: false,
													allowAddNewData: true,
													stackItems: false,
													renderFieldBtns: false,
													addNewDataOnBlur: true,
													forceSameValueQuery: true,
													listeners: {
														newitem: function(bs,v, f){
															bs.mode = 'local';
															var newObj = {
																id: v,
																cat_list: v
															};
															bs.addItem(newObj);
														}
													}
												}]
											},{
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("GROUP"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [
													new Ext.form.ComboBox({
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("GROUP"))?>',
													hiddenName:'cat_entity',
													store: new Ext.data.ArrayStore({
														fields: ['cat_entity_sname', 'cat_entity_lname'],
														data : <? $szotar = Common::szotar("ENTITY"); echo Common::arr2jsobj($szotar["ENTITY"]); ?>
													}),
													valueField:'cat_entity_sname',
													displayField:'cat_entity_lname',
													editable: false,
													mode: 'local',
													triggerAction: 'all',
													emptyText:'...',
													selectOnFocus:true,
													allowBlank: false,
													blankText: '<?=$this->db->escape_str($this->lang->line("THIS_FIELD_IS_REQUIRED"))?>',
													value: record.data.catEntity,
													anchor:'100%'
													})
												]
											},{
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("REQUIRED"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [{
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("REQUIRED"))?>',
													name: 'cat_required',
													xtype: 'checkbox',
													inputValue: 'I',
													checked: record.data.catRequired == 'I' ? true : false
												}]
											},((record.data.catEntity == 'MAJ')?({
												xtype:'fieldset',
												title: '<?=$this->db->escape_str($this->lang->line("EMPHASIZED"))?>',
												autoHeight:true,
												layout: {
													type: 'anchor'
												},
												items: [{
													fieldLabel: '<?=$this->db->escape_str($this->lang->line("EMPHASIZED"))?>',
													name: 'cat_highlight',
													xtype: 'checkbox',
													inputValue: 'I',
													checked: record.data.catHighlight == 'I' ? true : false
												}]
											}):({xtype: 'hidden'}))
										]

									})

								}

							],

							bbar: {
								items: [{
									text: '<?=$this->db->escape_str($this->lang->line("SAVE"))?>',
									handler: save,
									icon: '<?=MEDIA?>icon/disk.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("CANCEL"))?>',
									handler: close,
									icon: '<?=MEDIA?>icon/cancel.png'
								}, {
									xtype: 'tbseparator'
								},{
									text: '<?=$this->db->escape_str($this->lang->line("RESET"))?>',
									handler: function() {
										categoryForm.getForm().reset();
									}
								}],
								buttonAlign : 'right'
							}

					});
					winCategory.show(this);

				}

			},

			border: false,
			frame:false,

			tbar: {
				items: [{
						icon: '<?=MEDIA?>icon/application_form_add.png',
						text: '<?=$this->db->escape_str($this->lang->line("ADD_NEW_PROPERTY"))?>',
						handler: function(){
							grid.fireEvent('rowdblclick', grid, 'new', new Object());
						}
					}, {
							xtype: 'tbseparator'
					}, {
						icon: '<?=MEDIA?>icon/application_form_delete.png',
						text: '<?=$this->db->escape_str($this->lang->line("CANCEL_CATEGORY"))?>',
						ref: '../removeBtn',
						disabled: true,
						handler: function(){
							Ext.MessageBox.confirm('<?=$this->db->escape_str($this->lang->line("CONFIRMATION"))?>', '<?=$this->db->escape_str($this->lang->line("ARE_YOU_SURE_YOU_WOULD_LIKE_TO_DELETE_THE_CATEGORY_BELOW"))?> (' + grid.getSelectionModel().getSelections()[0].data.catName + ')?' , function(btn) {
								if(btn == 'yes') {
									Ext.Ajax.request({url: '<?=site_url()?>admin/category_insert_update', params: 'del=1&catId=' + grid.getSelectionModel().getSelections()[0].data.catId, success: function() {
										Ext.get('center').load({url: '<?=site_url()?>admin/category', scripts:true});
										}
									});
								}
							});
						}
					}
				]
			}

		});

		grid.render('grid-table-category');

		grid.getSelectionModel().on('selectionchange', function(sm){
			grid.removeBtn.setDisabled(sm.getCount() < 1);
		});

		function save() {
			if(!categoryForm.getForm().isValid()) {
				Ext.Msg.show({
					title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
					msg: '<?=$this->db->escape_str($this->lang->line("PLEASE_CORRECT_THE_ERRORS"))?>',
					buttons: Ext.Msg.OK,
					icon: Ext.MessageBox.WARNING
				});
			} else {
				if(categoryForm.getForm().isDirty()) {
					categoryForm.getForm().submit({
						url: '<?=site_url()?>admin/category_insert_update',
						success: function(form, resp){
							if(resp.result.error) {
								Ext.Msg.show({
									title:'<?=$this->db->escape_str($this->lang->line("ERROR"))?>',
									msg: resp.result.error,
									buttons: Ext.Msg.OK,
									icon: Ext.MessageBox.ERROR
								});
							} else {
								winCategory.close();
							}
						}
					});
				} else {
					winCategory.close();
				}
			}
		};

		function close() {
			winCategory.close();
		};

	})
</script>


<div id="grid-table-category"></div>